var express = require('express');
var router = express.Router();
// //引入mysql
// const mysql = require('mysql')
const mydbsql = require('../db.js')
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express123' });
});

router.get('/login', function (req, res, next) {
  res.render('login', { title: 'Express123' });
});

router.get('/register', function (req, res, next) {
  res.render('register', { title: 'Express123' });
});

router.post('/login', async function (req, res, next) {
  let { username, password } = req.body
  let sql1 = `select * from user where username = '${username}' and password = '${password}' ;`
  let res1 = await mydbsql(sql1)
  console.log(res1.results);
  if (res1.results.length <= 0) {
    let data = {
      msg: '用户名密码不匹配',
      status: 10004,
    }
    res.send(data)
    return
  }
  let value = res1.results
  let data = {
    msg: 'ok',
    status: 10001,
    data: value[0]
  }
  res.send(data)

});
router.post('/register', async function (req, res, next) {
  let { username, password, repwd } = req.body
  username = username.trim()
  password = password.trim()
  repwd = repwd.trim()
  //2. 必须做一些数据验证
  //2.1 是否为空
  if (username == '' || !password || !repwd) {

    let data = {
      msg: '请传递必要参数',
      status: 10003,
    }

    res.send(data)
    return //都已经send响应结果了，没必要再往下执行
  }
  //2. 格式判断： 长度
  //用户名不到小于5位 不能大于 15位
  if (username.length < 5 || username.length > 15) {

    let data = {
      msg: '用户名不到小于5位 不能大于 15位',
      status: 10003,
    }

    res.send(data)
    return
  }
  //两次密码不一致

  let sql0 = `select * from user where username = '${username}' ;`
  let res1 = await mydbsql(sql0)
  console.log(res1.results.length);
  if (res1.results.length !== 0) {

    let data = {
      msg: '用户名已存在',
      status: 10002,
    }
    console.log(data);
    res.send(data)
    return
  }

  let time = Date.now()
  let sql3 = `INSERT INTO user ( username,password,time ) VALUES ( '${username}','${password}','${time}' )`
  let res2 = await mydbsql(sql3)

  if (res2.results.affectedRows !== 1) {
    res.send('注册失败')
    return
  }
  let data = {
    msg: 'ok',
    status: 10001,
  }
  console.log(data);
  res.send(data)
});



module.exports = router;
